package top.sdwu_top.kbase.common.handler;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import top.sdwu_top.kbase.common.model.Wrapper;
import top.sdwu_top.kbase.entity.KbaseAuthUser;
import top.sdwu_top.kbase.util.JwtTokenUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Slf4j
@Component
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        log.info("发放token");

        KbaseAuthUser userDetails = (KbaseAuthUser) authentication.getPrincipal();

        String jwtToken = JwtTokenUtil.generateToken(userDetails.getUsername(), 7200, "_secret");
        Map<String, Object> result = Maps.newHashMap();
        result.put("token", jwtToken);
        result.put("expire", 7200);
        httpServletResponse.getWriter().write(JSON.toJSONString(Wrapper.<Map<String, Object>>ok(result)));
    }
}
